package org.ggn.dao;

import org.ggn.model.User;
import org.ggn.exception.UserException;
import org.ggn.util.HibernateUtil;
import org.hibernate.Session;

public class UserDao implements UDao {

	@Override
	public void add(User user) {
		Session session = null;
		try {
			session = HibernateUtil.openSession();
			session.beginTransaction();

			if(user.getUsername()==null){
				throw new UserException("用户名不能为空");
			}
			if(user.getPassword()==null){
				throw new UserException("密码不能为空");
			}
			if(user.getPassword().length()<6){
				throw new UserException("密码不能小于六位");
			}
			User u = (User) session.createQuery("select us from User us where username like ?")
					.setParameter(0,user.getUsername()).uniqueResult();
			if(u!=null){
				throw new UserException("用户已存在");
			}
			session.save(user);
			
			session.getTransaction().commit();
		} 
		finally{
			HibernateUtil.close(session);
		}
	}

	@Override
	public void delete(User user) {
		Session session = null;
		try {
			session = HibernateUtil.openSession();
			session.beginTransaction();
			
			if(user==null){
				throw new UserException("用户名不能为空");
			}
			session.delete(user);
			
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			if(session!=null){
				session.getTransaction().rollback();
			}
		}finally{
			HibernateUtil.close(session);
		}

	}

	@Override
	public void update(User user) {
		Session session = null;
		try {
			session = HibernateUtil.openSession();
			session.beginTransaction();
			User u = (User)session.load(User.class, user.getId());
			if(u==null){
				throw new UserException("更新的用户不存在");
			}
			if(user.getPassword().length()<6){
				throw new UserException("密码不能小于6位");
			}
			u.setNickname(user.getNickname());
			u.setPassword(user.getPassword());
			u.setLike(user.getLike());
			u.setFlist(user.getFlist());
			session.update(u);
			
			session.getTransaction().commit();
		} finally{
			HibernateUtil.close(session);
		}
	}

	@Override
	public User load(int id) {
		Session session = null;
		User u = null;
		try {
			session = HibernateUtil.openSession();
			if(id==0){
				throw new UserException("查找不存在");
			}
			u = (User)session.load(User.class, id);
			return u;
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			HibernateUtil.close(session);
		}
		return u;
	}
	@Override
	public User login(String username,String password){
		Session session = null;
		User u = null;
		try {
			session = HibernateUtil.openSession();
			u = (User) session.createQuery("select us from User us where username like ?")
					.setParameter(0, username).uniqueResult();
			if(u==null){
				throw new UserException("用户不存在");
			}
			if(!u.getPassword().equals(password)){
				throw new UserException("密码错误");
			}
			
		} finally{
			HibernateUtil.close(session);
		}
		return u;
	}

}
